package com.example.demo.controller;

import com.example.demo.config.shiro.ShiroConstant;
import com.example.demo.entity.access.Menu;
import com.example.demo.entity.access.User;
import com.example.demo.service.access.IMenuService;
import com.example.demo.service.access.IUserService;
import com.example.demo.utils.MessageBody;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Controller
public class LogonAction {
    private transient static final Logger LOGGER = LoggerFactory.getLogger(LogonAction.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private IMenuService menuService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(User user, boolean rememberMe) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword(), rememberMe);
        try {
            subject.login(token);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return "system/error";
        }
        return "redirect:/index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String goLogonPage() {
        return "system/login";
    }


    @RequestMapping("/index")
    public String index(HttpServletRequest request) {
        List<Menu> menus = menuService.listMenusAsTree();
        request.setAttribute("menus", menus);
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession(true);
        Object username = subject.getPrincipal();
        if (username != null) {
            User user = userService.findByUsername(username.toString());
            if (user != null) {
                session.setAttribute("user", user);
                LOGGER.info("用户:{}登录系统", user);
            }
        }
        return "system/index";
    }

    @ResponseBody
    @RequestMapping("/register")
    public Object register(User user) {
        String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
        String md5Pwd = new Md5Hash(user.getPassword(), salt, ShiroConstant.ENCRYPT_NUMS).toString();
        user.setCredentialssalt(salt);
        user.setPassword(md5Pwd);
        user.setCreatedate(Calendar.getInstance().getTime());
        MessageBody result = userService.registerUser(user);
        return result;
    }

    @ResponseBody
    @RequestMapping("/update")
    public Object update(User user) {
        String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
        String md5Pwd = new Md5Hash(user.getPassword(), salt, ShiroConstant.ENCRYPT_NUMS).toString();
        user.setCredentialssalt(salt);
        user.setPassword(md5Pwd);
        MessageBody result = userService.updateUser(user);
        return result;
    }

    @RequestMapping("/addCookie")
    @ResponseBody
    public String addCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("test", "111");
        cookie.setPath("/test");
        response.addCookie(cookie);
        return "success";
    }

    @RequestMapping("/cookies")
    @ResponseBody
    public Object getCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        return cookies;
    }

    @RequestMapping("/logout")
    public String logout(){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return "redirect:system/login";
    }

}
